﻿using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using t01.Models;
using t01.Services;

namespace t01.ViewModels;

public partial class MainWindowViewModel : ViewModelBase
{

    private readonly IPoetryStorage _poetryStorage;

    private string? _message;

    // dependency inject: Repo inject into ViewModel
    public MainWindowViewModel(IPoetryStorage poetryStorage)
    {
        _poetryStorage = poetryStorage;
        // let SayHelloCommand method bind with SayHello method
        SayHelloCommand = new AsyncRelayCommand(SayHello);
        InitDatabaseCommand = new AsyncRelayCommand(InitDatabase);
        InsertCommand = new AsyncRelayCommand(InsertAsync);
        ListAllCommand = new AsyncRelayCommand(ListAsync);
    }



    public string Message
    {
        get => _message ??= "";
        set => SetProperty(ref _message, value);
    }


    public async Task SayHello()
    {
        // NOTE: use probe service
        await GetDataFromNet();
        Message = "Hello World";
    }



    public ICommand SayHelloCommand { get; }


    public async Task InitDatabase()
    {
        await _poetryStorage.InitializeAsync();
    }

    public ICommand InitDatabaseCommand
    {
        get;
    }

    public async Task InsertAsync()
    {
        var poetry = new Poetry
        {
            Name = "Name" + new Random().Next()
        };
        await _poetryStorage.InsertAsync(poetry);
    }

    public ICommand InsertCommand
    {
        get;
    }


    // public async Task ListAllAsync()
    // {
    //     await _poetryStorage.ListAsync();
    // }


    public ObservableCollection<Poetry> Poetries { get; set; } = new(); // same to: new ObservableCollection

    public async Task ListAsync()
    {
        var poetries = await _poetryStorage.ListAsync();
        Poetries.Clear();
        foreach (var p in poetries)
        {
            Poetries.Add(p);
        }
    }

    public ICommand ListAllCommand { get; set; }




}
